﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using HT.Future.Application;
using HT.Future.Common;
using HT.Future.Entities;
using HT.Future.IService;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Linq;

namespace HT.Future.TxApi.Controllers
{
    [ApiVersion("1.0")]
    [Authorize]
    [Route("api/[controller]")]
    public class WxUserController : BaseController
    {
        private readonly IWxUserService _service;

        public WxUserController(IMapper mapper, IWxUserService service) : base(mapper)
        {
            this._service = service;
        }

        /// <summary>
        /// 获取登录用户的初始化数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("init")]
        public async Task<ApiResult<object>> GetInitData([FromServices] IBusinessService businessService)
        {
            var businesses = await businessService.GetBusinessesAsync(UserId);
            return new { businesses };
        }

        /// <summary>
        /// 用户信息授权
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost("grant")]
        public async Task<ApiResult<WxUser>> GrantUserInfo([FromBody] WxUser user)
        {
            user.FaceUrl = await SaveFaceAsync(user.FaceUrl);
            var userinfo = await _service.GrantAsync(user);
            return userinfo;
        }

        /// <summary>
        /// 设置默认商户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("setStore/{id}")]
        public async Task<ApiResult> SetDefaultBusiness(int id)
        {
            var user = await _service.GetByIdAsync<WxUser>(UserId);
            user.DefualtBusiness = id;
            await _service.CommitAsync();
            return Content("设置成功");
        }

        /// <summary>
        /// 上传头像
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private async Task<string> SaveFaceAsync(string url)
        {
            var config = HttpContext.RequestServices.GetService<IConfiguration>();
            var fileserver = config.GetSection("AppConfig:FileServer").Value;
            var res = await UtilHelper.RequestAsync($"{fileserver}/api/user", new { item1 = url });
            return res;
        }
    }
}
